<template>
  <div class="table-container">
    <el-table
      ref="taskTableRef"
      class="mytable"
      :data="state.list"
      v-bind="$attrs"
      row-key="id"
      :expand-row-keys="expands"
      @expand-change="expandChange"
      stripe
      style="width: 100%"
      v-loading="state.loading"
      @select="onSelect"
      @selection-change="onSelectionChange"
      :header-cell-style="{
        background: '#E0E0E0',
        color: '#2B2B2B',
        fontWeight: 500
      }"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        :reserve-selection="true"
        width="30"
        v-if="config.isSelection"
      />
      <el-table-column
        type="index"
        label="序号"
        width="66"
        v-if="config.isSerialNo"
      />
      <el-table-column width="40" type="expand" v-if="config.isExtend">
        <template #default="escope">
          <!-- 第二级表格 -->
          <el-table :data="escope.row[extendTable.dataProp]" border>
            <el-table-column
              type="index"
              label="序号"
              width="66"
              v-if="extendTable.inx"
            />
            <el-table-column
              v-for="(eitem, index) in extendTable.header"
              :key="index"
              show-overflow-tooltip
              :prop="eitem.key"
              :width="eitem.colWidth"
              :label="eitem.title"
            >
              <template v-slot="scope">
                <template v-if="eitem.type === 'image'">
                  <img
                    :src="scope.row[eitem.key]"
                    :width="eitem.width"
                    :height="eitem.height"
                  />
                </template>
                <template v-if="eitem.type === 'slot'">
                  <slot :slotData="scope.row" :slotColumn="eitem"></slot>
                </template>
                <template v-else>
                  {{ scope.row[eitem.key] }}
                </template>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="300"
              v-if="extendTable.isOperate"
              fixed="right"
            >
              <template v-slot="scope">
                <template v-for="(ev, inx) in extendTable.extendBtn" :key="inx">
                  <el-button
                    class="my-table__btn"
                    size="default"
                    plain
                    :disabled="
                      (ev.disable && ev.disable(scope.row)) ||
                      scope.row?.disable
                    "
                    v-if="
                      ((ev.hide && ev.hide(scope.row)) || !ev.hide) &&
                      buttonDisplayOrNot(ev.btns, ev.btnCode)
                    "
                    @click="onClickChild(scope.row, ev, escope.row)"
                    v-loading="ev?.loading ? scope.row?.disable : false"
                    :type="ev?.type"
                    :color="ev?.color"
                    >{{ ev.text }}</el-button
                  >
                </template>
              </template>
            </el-table-column>
          </el-table>
          <!-- 第二级描述 -->
          <div v-if="extendTable.describe" class="describe">
            <div class="title">{{ extendTable.describeTitle }}</div>
            <div
              v-for="(desItem, index) in escope.row[extendTable.describeProp]"
            >
              <!-- {{ index + 1 + "、" + desItem.content }} -->
              {{ index + 1 + '、' + desItem.itemName + '：' + desItem.content }}
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        v-for="(item, index) in setHeader"
        :key="index"
        show-overflow-tooltip
        :prop="item.key"
        :width="item.colWidth"
        :label="item.title"
      >
        <template v-slot="scope">
          <template v-if="item.type === 'image'">
            <img
              :src="scope.row[item.key]"
              :width="item.width"
              :height="item.height"
            />
          </template>
          <template v-if="item.type === 'slot'">
            <slot :slotData="scope.row" :slotColumn="item"></slot>
          </template>
          <template v-else>
            {{
              scope.row[item.key] === '' || scope.row[item.key].length === 0
                ? '-'
                : scope.row[item.key]
            }}
          </template>
        </template>
      </el-table-column>
      <!-- <el-table-column class="operation" label="操作" width="200" v-if="config.isOperate"> -->
      <el-table-column
        label="操作"
        fixed="right"
        :width="operateWidth()"
        v-if="config.isOperate"
      >
        <template v-slot="scope">
          <template v-for="(v, inx) in columnBtn" :key="inx">
            <el-button
              class="my-table__btn"
              size="default"
              plain
              :disabled="
                (v.disable && v.disable(scope.row)) || scope.row?.disable
              "
              v-if="
                ((v.hide && v.hide(scope.row)) || !v.hide) &&
                buttonDisplayOrNot(v.btns, v.btnCode)
              "
              @click="onClick(scope.row, v)"
              v-loading="v?.loading ? scope.row?.disable : false"
              :type="v?.type"
              :color="v?.color"
              >{{ v.text }}</el-button
            >
            <!--  -->
          </template>
        </template>
      </el-table-column>
      <template #empty>
        <!-- <el-empty description="暂无数据" /> -->
        <img
          v-if="themeConfig.primary == '#02AD82'"
          src="../../assets/noData.png"
          alt=""
        />
        <img
          v-else-if="themeConfig.primary == '#063C74'"
          src="../../assets/noData3.png"
          alt=""
        />
        <img
          v-else="themeConfig.primary == '#514FC2'"
          src="../../assets/noData2.png"
          alt=""
        />
      </template>
    </el-table>
    <div class="table-footer mt15" v-if="!config.noPage">
      <el-pagination
        v-model:current-page="state.page.pageNum"
        v-model:page-size="state.page.pageSize"
        :page-sizes="[10, 20, 30]"
        :total="state.page.total"
        layout="total, sizes, prev, pager, next, jumper"
        pager-count="3"
        background
        @size-change="onHandleSizeChange"
        @current-change="onHandleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts" name="netxTable">
import { reactive, computed, watch, ref, onMounted } from 'vue'
import { debounce } from '/@/utils/loading'
import { storeToRefs } from 'pinia'
import { useThemeConfig } from '/@/stores/themeConfig'
import '/@/theme/tableTool.scss'
import http from '/@/utils/http'
import { isEmpty } from 'lodash'
import { buttonDisplayOrNot } from '/@/utils/buttonBoolean'

const taskTableRef = ref()
// 定义父组件传过来的值
const props = defineProps({
  flash: {
    type: Boolean,
    default: false
  },
  first: {
    type: Boolean,
    default: true
  },
  //是否单选
  redio: {
    type: Boolean,
    default: false
  },
  //是否清空选择
  empty: {
    type: Boolean,
    default: false
  },
  //是否禁用选项
  selecta: {
    type: Boolean,
    default: false
  },
  // 表头内容
  header: {
    type: Array<EmptyObjectType>,
    default: () => []
  },
  // 配置项
  config: {
    type: Object,
    default: () => {}
  },
  param: {
    // 表格查询值
    type: Object,
    default: () => {}
  },
  extendTable: {
    type: Object,
    default: () => {}
  },
  columnBtn: {
    // 操作按钮
    type: Array<EmptyObjectType>,
    default: () => []
  },
  defaultList: {
    // 默认选中数组
    type: Array,
    default: () => []
  }
})

// 定义子组件向父组件传值/事件
const emit = defineEmits(['listenClick', 'dataList', 'expandChange'])

// 定义变量内容
const storesThemeConfig = useThemeConfig()
const { themeConfig } = storeToRefs(storesThemeConfig)
const state = reactive({
  list: [],
  page: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  selectlist: [] as EmptyObjectType[],
  checkListAll: true,
  checkListIndeterminate: false,
  loading: false
})

// 设置 tool header 数据
const setHeader = computed(() => {
  return props.header.filter((item) => !item.hide)
})

//获取列表
const onList = () => {
  let search = JSON.parse(JSON.stringify(props.param))
  let params: any = {}
  if (!props.config?.noPage) {
    //不隐藏分页  即有分页得时候
    params.pn = state.page.pageNum
    params.ps = state.page.pageSize
  }
  for (let key of Object.keys(search)) {
    params[key] = search[key]
  }
  onListApi(params)
}

//列表搜索接口
const onListApi = async (params: any) => {
  state.loading = true
  try {
    let res = await http[props.config.listHttp](props.config.listApi, params)
    if (res?.code === 0) {
      if (!props.config?.noPage) {
        state.list = res.data.records
        state.page.total = res.data.total
      } else {
        state.list = res.data
      }
      emit('dataList', res.data)
      if (props.defaultList.length != 0) {
        state.list.forEach((item: any) => {
          props.defaultList.forEach((j: any) => {
            if (item.id == j.id) {
              taskTableRef.value.toggleRowSelection(item, true)
            }
          })
        })
      }
      state.loading = false
    } else {
      state.loading = false
    }
  } catch (error) {
    state.loading = false
  }
}

//判断操作的width是否有值,有值取值,没值默认200
const operateWidth = () => {
  if (props.config.operateName) {
    return props.config.operateWidth == null ? 200 : props.config.operateWidth
  } else {
    let arr = <any>[]
    props.columnBtn.forEach((v: any) => {
      if (v.hide && buttonDisplayOrNot(v.btns, v.btnCode)) {
        arr.push(v)
      }
    })
    return arr.length * 110
  }
}

const selectable = ref()
watch(
  () => [props.flash, props.empty, props.selecta, props.first],
  () => {
    if (props.empty) {
      taskTableRef.value.clearSelection()
      emit('listenClick', 'emptyBack', false)
    }
    if (props.selecta) {
      selectable.value = (row: any, index: any) => {
        return row.taskFlag == 0 ? true : false
      }
    }
    if (!props.config?.noPage) {
      //不隐藏分页  即有分页的时候
      state.page.pageNum = 1
    }
    if (props.first) {
      onList() //获取列表
    } else {
      state.list = []
    }
  },
  { immediate: true }
)
const onSelect = (selection: any, row: any) => {
  if (selection.length > 1 && props.redio) {
    let del_row = selection.shift()
    taskTableRef.value.toggleRowSelection(del_row, false) // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
  let obj = {
    selection: selection,
    row: row
  }
  emit('listenClick', 'onSelect', obj)
}
// 表格多选改变时，用于导出
const onSelectionChange = (val: EmptyObjectType[]) => {
  state.selectlist = val
  emit('listenClick', 'onSelectionChange', val)
}
// 多级表格展开时
const expands = ref<any>([])
const expandChange = (row: any, expandedRows: any) => {
  if (expandedRows.length) {
    //说明展开了
    expands.value = []
    if (row) {
      expands.value.push(row.id) //只展开当前行id，唯一标识
      emit('expandChange', row)
    }
  } else {
    //说明收起了
    expands.value = []
  }
}
// 点击操作栏按钮当前项(父Item)
const onClick = (row: any, val: any) => {
  emit('listenClick', val.name, row)
}
// 点击操作栏按钮当前项(子item)
const onClickChild = (row: any, val: any, parentRow: any) => {
  row['itemParentId'] = parentRow.id
  emit('listenClick', val.name, row, parentRow)
}
// 分页改变
const onHandleSizeChange = (val: number) => {
  state.page.pageSize = val
  onList() //获取列表
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.page.pageNum = val
  onList() //获取列表
}
// 搜索时，分页还原成默认
const pageReset = () => {
  state.page.pageNum = 1
  state.page.pageSize = 10
  onList() //获取列表
}

// 暴露变量
defineExpose({
  pageReset
})
</script>

<style scoped lang="scss">
.table-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-top: 10px;

  .el-table {
    flex: 1;
  }

  .table-footer {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}

.describe {
  padding: 10px;

  .title {
    margin-bottom: 10px;
    font-size: 18px;
    font-weight: 600;
  }
}

.my-table {
  &__btn {
    margin: 5px;
  }
}
</style>
<style>
.el-button--primary.is-plain {
  --el-button-bg-color: #ffffff;
  --el-button-hover-text-color: var(--el-color-primary);
  --el-button-hover-bg-color: #ffffff;
}

.el-button--primary.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: var(--el-color-primary);
}
.el-button--warning.is-plain {
  --el-button-bg-color: #fdf6ec;
  --el-button-hover-text-color: #e6a23c;
  --el-button-hover-bg-color: #fdf6ec;
}

.el-button--warning.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #e6a23c;
}

.el-button--danger.is-plain {
  --el-button-bg-color: #fef0f0;
  --el-button-hover-text-color: #f56c6c;
  --el-button-hover-bg-color: #fef0f0;
}

.el-button--danger.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #f56c6c;
}
</style>
